<?php
namespace Payment\Notify;

use Payment\Common\PayException;
use Payment\Common\HsqTransConfig;
use Payment\Config;
use Payment\Utils\BaoFooRsaUtil;
use Payment\Utils\DataParser;


/**
 * Class MiNotify
 * 微信回调处理
 * @package Payment\Notify
 * @anthor yeran
 */
class HsqTransferNotify extends NotifyStrategy
{

    /**
     * MiNotify constructor.
     * @param array $config
     * @throws PayException
     */
    public function __construct(array $config)
    {
        parent::__construct($config);
        try {
            $this->config = new HsqTransConfig($config);
        } catch (PayException $e) {
            throw $e;
        }
    }

    /**
     * 获取返回的异步通知数据
     * @return array|bool
     * @author yeran
     */
    public function getNotifyData()
    {
        //支持直接读取input流
        $data = $_POST['req'] ?? file_get_contents('php://input');
        if(empty($data)){//如果参数为空,则不进行处理
            return false;
        }
        $tmp = explode("&",urldecode($data));
        $result_data = array();
        foreach($tmp as $val)
        {
            $tmp2 = explode("=",$val);
            $result_data[$tmp2[0]] = $tmp2[1];
        }
        if (empty($this->config->publicKey)) return false;
        $publicKey = $this->config->publicKey;
        $retData = $result_data['data_content'];
        //解密
        $decrypt = BaoFooRsaUtil::decryptByCERFile($retData, $publicKey);
        $data_content = DataParser::toArray($decrypt);
        return $data_content['trans_reqDatas']['trans_reqData'] ?? '';
    }

    /**
     * 检查异步通知的数据是否正确
     * @param array $data
     *
     * @author yeran
     * @return boolean
     */
    public function checkNotifyData(array $data)
    {
        // 检查返回数据签名是否正确
        return $this->verifySign($data);
    }

    /**
     * 检查微信返回的数据是否被篡改过
     * @param array $retData
     * @return boolean
     * @author yeran
     */
    protected function verifySign(array $retData)
    {
        return true;
    }

    /**
     *
     * 封装回调函数需要的数据格式
     *
     * @param array $data
     *
     * @return array
     * @author yeran
     */
    protected function getRetData(array $data)
    {
        $retData = $data;
        $retData['amount'] = bcmul($data['trans_money'] ?? 0, 100); //转账金额
        $retData['channel'] = Config::HSQ_TRANSFER;
        return $retData;
    }

    /**
     * 处理完后返回的数据格式
     * @param bool $flag
     * @param string $msg 通知信息，错误原因
     * @author yeran
     * @return string
     */
    protected function replyNotify($flag, $msg = 'OK')
    {
        // 默认为成功
        $return_code ='SUCCESS';
        if (!$flag) {
            $return_code ='FAIL';
        }
        return $return_code;
    }
}
